import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axios from '../../request/axios';

/**
 * 医生问诊记录接口定义
 * @interface DoctorInquiryRecord
 * @property {number} recordId - 记录ID
 * @property {number} userId - 用户ID
 * @property {string} userHeadPic - 用户头像URL
 * @property {string} doctorHeadPic - 医生头像URL
 * @property {string} nickName - 用户昵称
 * @property {number} inquiryTime - 问诊时间戳
 * @property {number} status - 评价状态：1=待评价，2=已评价
 */
interface DoctorInquiryRecord {
    recordId: number;
    userId: number;
    userHeadPic: string;
    doctorHeadPic: string;
    nickName: string;
    inquiryTime: number;
    status: number; // 1=待评价 2=已评价
}

/**
 * 历史记录状态接口定义
 * @interface HistoryState
 * @property {DoctorInquiryRecord[]} records - 问诊记录列表
 * @property {boolean} loading - 加载状态
 * @property {string | null} error - 错误信息
 * @property {boolean} hasMore - 是否还有更多数据
 * @property {number} page - 当前页码
 */
interface HistoryState {
    records: DoctorInquiryRecord[];
    loading: boolean;
    error: string | null;
    hasMore: boolean;
    page: number;
}

/**
 * 初始状态
 * @constant initialState
 */
const initialState: HistoryState = {
    records: [],
    loading: false,
    error: null,
    hasMore: true,
    page: 1,
};

/**
 * 获取历史问诊记录的异步 thunk
 * @function fetchHistoryRecords
 * @param {Object} params - 请求参数
 * @param {number} params.page - 页码
 * @param {number} params.count - 每页数量
 * @returns {Promise} 返回问诊记录数据
 */
export const fetchHistoryRecords = createAsyncThunk(
    'history/fetchRecords',
    async (params: { page: number; count: number }, { rejectWithValue }) => {
        try {
            // 检查医生登录状态
            const doctorInfoStr = localStorage.getItem('doctorInfo');
            if (!doctorInfoStr) {
                throw new Error('请先登录');
            }
            const { doctorId, sessionId } = JSON.parse(doctorInfoStr);

            // 发送请求获取历史记录
            const response = await axios.get('/health/doctor/inquiry/verify/v1/findHistoryInquiryRecord', {
                headers: { doctorId, sessionId },
                params
            });

            // 处理响应数据
            if (response.data.status === '0000') {
                return response.data;
            } else {
                return rejectWithValue(response.data.message || '加载失败');
            }
        } catch (error) {
            // 错误处理
            if (error instanceof Error) {
                return rejectWithValue(error.message);
            }
            return rejectWithValue('加载失败');
        }
    }
);

/**
 * 历史记录 Slice
 * 管理历史问诊记录的状态和操作
 */
const historySlice = createSlice({
    name: 'history',
    initialState,
    reducers: {
        /**
         * 重置历史记录状态
         * @function resetHistory
         */
        resetHistory: (state) => {
            state.records = [];
            state.page = 1;
            state.hasMore = true;
            state.error = null;
        },
    },
    extraReducers: (builder) => {
        builder
            // 处理加载中状态
            .addCase(fetchHistoryRecords.pending, (state) => {
                state.loading = true;
                state.error = null;
            })
            // 处理加载成功状态
            .addCase(fetchHistoryRecords.fulfilled, (state, action) => {
                state.loading = false;
                const newRecords = action.payload.result || [];
                state.records = [...state.records, ...newRecords];
                state.hasMore = newRecords.length === action.meta.arg.count;
                state.page += 1;
            })
            // 处理加载失败状态
            .addCase(fetchHistoryRecords.rejected, (state, action) => {
                state.loading = false;
                state.error = action.payload as string || '加载失败，请稍后重试';
            });
    },
});

export const { resetHistory } = historySlice.actions;
export default historySlice.reducer; 